package com.example.stlink.configs.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.stlink.R;
import com.example.stlink.model.domain.Course;

import java.util.List;

/**
 * 用于将课程数据渲染进ListView控件中进行显示
 */
public class CourseChooseAdapter extends RecyclerView.Adapter<CourseChooseAdapter.ViewHolder> implements View.OnClickListener  {

    private com.example.stlink.configs.onRecyclerViewItemClickListener  onRecyclerViewItemClickListener;
    private RecyclerView rvParent;

    private final List<Course> mCourseData;

    private final Context mContext;
    private final int resourceId;

    public CourseChooseAdapter(@NonNull Context context, int resourceId, @NonNull List<Course> data) {
        this.mContext = context;
        this.mCourseData = data;
        this.resourceId = resourceId;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //指定一个父控件
        rvParent = (RecyclerView) parent;

        View view = LayoutInflater.from(mContext)
                .inflate(resourceId, parent, false);
        ViewHolder holder = new ViewHolder(view);
        view.setOnClickListener(this);

        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Course course = mCourseData.get(position);
        Glide.with(mContext).load(course.getmCoursePhoto()).into(holder.ivCoursePhoto);
        holder.tvCourseName.setText(course.getmCourseName());
    }

    @Override
    public int getItemCount() {
        return mCourseData.size();
    }

    //重载点击事件，指定点击事件时执行自定义的onItemClick
    @Override
    public void onClick(View view) {
        int position = rvParent.getChildAdapterPosition(view);
        if (onRecyclerViewItemClickListener != null){
            onRecyclerViewItemClickListener.onItemClick(rvParent, view, position);
        }
    }

    //实例化自定义接口
    public void setOnItemClickListener(com.example.stlink.configs.onRecyclerViewItemClickListener onRecyclerViewItemClickListener) {
        this.onRecyclerViewItemClickListener = onRecyclerViewItemClickListener;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView ivCoursePhoto;
        TextView tvCourseName;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            ivCoursePhoto = itemView.findViewById(R.id.iv_course_photo);
            tvCourseName = itemView.findViewById(R.id.tv_course_name);
        }
    }
}
